package com.shujia.scala

import scala.io.Source

object Demo31Match {
  def main(args: Array[String]): Unit = {
    //1、基本数据类型
    val i = 400
    i match {
      case 100 => println("i等于100")
      case 200 => println("i等于200")
      case 300 => println("i等于300")
      case _ => println("其他")
    }

    //2、字符串
    val name = "张三"
    name match {
      case "张三" => println("张三")
      case "李四" => println("李四")
      case "王五" => println("王五")
      case _ => println("其他")
    }

    //3、枚举enum
    val a = Weekday.B
    a match {
      case Weekday.A => println("A")
      case Weekday.B => println("B")
      case Weekday.C => println("C")
      case _ => println("其他")
    }

    //4、类型
    val obj: Any = 11
    obj match {
      case i: Int => println(s"${i}是一个Int类型")
      case str: String => println(s"${str}是一个String类型")
      case d: Double => println(s"${d}是一个Double类型")
      case _ => println(s"${obj}是其他类型")
    }

    //5、样例类的对象
    case class User(id: String, name: String, age: Int)
    val user1: User = User("001", "张三", 23)
    user1 match {
      case User("001", "张三", 23) => println(user1)
      case User("002", "李四", 24) => println(user1)
      case User("003", "王五", 24) => println(user1)
    }

    //应用
    val names: Map[String, String] = Map("001" -> "张三", "002" -> "李四")
    //Option：可选的值
    val option: Option[String] = names.get("003")
    //match可以有返回值
    val name1: String = option match {
      case Some(v) => v
      case None => "默认值"
    }
    println(name1)

    //在map方法中使用
    val users: List[(String, (String, Int))] = List(
      ("001", ("张三", 23)),
      ("002", ("李四", 23)),
      ("003", ("王五", 23))
    )

    val names1: List[String] = users.map(kv => kv._2._1)
    println(names1)

    users.map {
      case (_, (name, age)) => name
    }.foreach(println)

    //统计学生的总分
    val scores: List[String] = Source.fromFile("data/score.txt").getLines().toList

    scores
      .map(_.split(","))
      .map {
        //匹配数组
        case Array(sid, _, score) => (sid, score.toDouble)
      }
      .groupBy { case (sid, _) => sid }
      .mapValues(value =>
        value.map { case (_, score) => score }.sum
      )
      .foreach(println)


    val list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
    list.map(x =>
      x % 2 match {
        case 1 => x + 1
        case 0 => x * 2
      }
    ).foreach(println)
  }
}













